from . import admin
from app import db
from app.schemas import CategoryOutSchema
from app.models import Category
from flask import render_template, request
from app.some_func import wapper, fail_api, success_api, table_api
#  分类管理
@admin.get('/category')
@wapper
def category_main():
    return render_template('admin/category/main.html')
# 表格数据
@admin.get('/category/data')
@wapper
def category_table():
    category = request.args.get('category')
    filters = []
    if category:
        filters.append(Category.name.contains(category))
    categorys = Category.query.filter(*filters).paginate(page=request.args.get('page', type=int),per_page=request.args.get('limit', type=int),error_out=False)
    return table_api(data=CategoryOutSchema(many=True).dump(categorys), count=categorys.total)
# 增加分类
@admin.get('/category/add')
@wapper
def category_add():
    return render_template('admin/category/add.html')
# 分类保存
@admin.post('/category/save')
@wapper
def category_save():
    if not request.json.get('name'):
        return fail_api(msg="所有内容不得为空")
    name = request.json.get('name')
    category = Category(name=name)
    db.session.add(category)
    db.session.commit()
    return success_api(msg="增加成功")
# 编辑分类
@admin.get('/category/edit/<int:id>')
@wapper
def category_edit(id):
    category = Category.query.filter_by(id=id).first()
    return render_template('admin/category/edit.html', category=category)
# 删除分类
@admin.delete('/category/remove/<int:id>')
@wapper
def category_delete(id):
    category = Category.query.filter_by(id=id).first()
    res = Category.query.filter_by(id=id).delete()
    db.session.commit()
    if not res:
        return fail_api(msg="删除失败")
    return success_api(msg="删除成功")
# 更新分类
@admin.put('/category/update')
@wapper
def category_update():
    if not request.json.get('name'):
        return fail_api(msg="所有内容不得为空")
    id = request.json.get('id')
    name = request.json.get('name')
    Category.query.filter_by(id=id).update({'name':name})
    db.session.commit()
    return success_api(msg="更新成功")